package com.sunny.shop.api.v1;

import com.sunny.shop.core.LocalUser;
import com.sunny.shop.core.interceptors.ScopeLevel;
import com.sunny.shop.exception.httpe.NotFoundException;
import com.sunny.shop.exception.httpe.Success;
import com.sunny.shop.model.User;
import com.sunny.shop.repository.UserRepository;
import com.sunny.shop.util.CommonUtil;
import com.sunny.shop.util.FileNameUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private UserRepository userRepository;
    //文件扩展名校验
    private String arrsuffix[] = {"PNG","JPG","JPEG","BMP","GIF","SVG"};

    @ScopeLevel
    @PostMapping(value ="/active")
    public Map<String,String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Long uid = LocalUser.getUser().getId();
        User user = userRepository.findOneById(uid);
        if(user == null) {
            throw new NotFoundException(10005);
        }
        try {
            if (file.isEmpty()) {
                throw new NotFoundException(70001);
            } else {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                if (!Arrays.asList(arrsuffix).contains(suffix.toUpperCase())) {
                    throw new NotFoundException(10007);
                }
                //获取文件名称
                String filenameup = file.getOriginalFilename();
                //定义要上传文件 的存放路径
                String localPath = ResourceUtils.getURL("classpath:").getPath() + "/static/";
                filenameup = FileNameUtil.getFileName(filenameup);
                File dest = new File(localPath,filenameup);
                if (!dest.exists()) {
                    dest.mkdirs();
                }
                file.transferTo(dest);//拷贝文件到指定路径储存
                HashMap<String, String> str = new HashMap<>();
                str.put("url" , "/" + filenameup);
                user.setHeadImg(filenameup);
                userRepository.save(user);
                return str;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回
        throw new NotFoundException(10007);
    }
}
